package com.yuanlrc.base.service.admin;


import com.yuanlrc.base.bean.PageBean;
import com.yuanlrc.base.dao.admin.FacultiesDao;
import com.yuanlrc.base.entity.admin.Faculties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 学院列表service
 */
@Service
public class FacultiesService {

    @Autowired
    private FacultiesDao facultiesDao;

    /**
     * 根据学院id查询
     * @param id
     * @return
     */
    public Faculties find(Long id){
        return facultiesDao.find(id);
    }

    /**
     * 查询所有学院
     * @returnpu
     */
    public List<Faculties> findAll(){
        return facultiesDao.findAll();
    }

    /**
     * 按照学院名查找用户
     * @param name
     * @return
     */
    public Faculties findByName(String name){
        return facultiesDao.findByName(name);
    }

    /**
     * 学院添加/编辑操作
     * @param faculties
     * @return
     */
    public Faculties save(Faculties faculties){
        return facultiesDao.save(faculties);
    }


    /**
     * 分页查询学院列表
     * @param faculties
     * @param pageBean
     * @return
     */
    public PageBean<Faculties> findList(Faculties faculties,PageBean<Faculties> pageBean){
        ExampleMatcher withMatcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("num",ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Faculties> example = Example.of(faculties, withMatcher);
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage()-1, pageBean.getPageSize());
        Page<Faculties> findAll = facultiesDao.findAll(example, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }


    /**
     * 判断学院编号是否存在，添加和编辑均可判断
     * @param num
     * @return
     */
    public boolean isExistByNum(String num){
        Faculties faculties = facultiesDao.findByNum(num);
        if(faculties != null){
            return true;
        }
        return false;
    }

    /**
     * 判断学院名是否存在，添加和编辑均可判断
     * @param name
     * @param id
     * @return
     */
    public boolean isExistByName(String name,Long id){
        Faculties faculties = facultiesDao.findByName(name);
        if(faculties != null){
            //表示学院名存在，接下来判断是否是编辑学院的本身
            if(faculties.getId().longValue() != id.longValue()){
                return true;
            }
        }
        return false;
    }

    /**
     * 按照学院id删除
     * @param id
     */
    public void delete(Long id){
        facultiesDao.deleteById(id);
    }

    /**
     * 返回学院总数
     * @return
     */
    public long total(){
        return facultiesDao.count();
    }


}
